/**
 * (C) 2007 Stefan Arentz & Polar Rose AB
 *
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.polarrose.jetty.deployer.maven;

import com.sun.org.apache.xpath.internal.XPathAPI;
import org.mortbay.log.Log;
import org.w3c.dom.Document;
import org.w3c.dom.Node;

import javax.xml.parsers.DocumentBuilderFactory;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * @author Stefan Arentz
 */

public class MavenUtil
{
    static URL getArtifactUrl(URL repositoryUrl, MavenArtifact artifact, String snapshotTimestamp, String snapshotBuildNumber) throws MalformedURLException
    {
        String v = artifact.getVersion();

        if (!v.endsWith("-SNAPSHOT")) {
            throw new IllegalArgumentException("Getting the snapshot artifact url is only supported for -SNAPSHOT versions");
        }

        v = v.substring(0, v.length() - 9);

        String path = "/" + artifact.getGroupId().replace(".", "/") + "/" + artifact.getArtifactId() + "/" + artifact.getVersion() + "/" + artifact.getArtifactId() + "-" + v + "-" +  snapshotTimestamp + "-" + snapshotBuildNumber + ".war";

        return new URL(repositoryUrl.toExternalForm() + path);
    }

    static MavenMetaData downloadMavenMetaData(URL repositoryUrl, MavenArtifact artifact) throws Exception
    {
        String path = "/" + artifact.getGroupId().replace(".", "/") + "/" + artifact.getArtifactId() + "/" + artifact.getVersion() + "/maven-metadata.xml";
        URL artifactMetaDataUrl = new URL(repositoryUrl + path);
        InputStream is = artifactMetaDataUrl.openStream();

        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        Document document = factory.newDocumentBuilder().parse(is);

        Node snapshotTimeStampNode  = XPathAPI.selectSingleNode(document, "/metadata/versioning/snapshot/timestamp");
        Node snapshotBuildNumberNode  = XPathAPI.selectSingleNode(document, "/metadata/versioning/snapshot/buildNumber");

        return new MavenMetaData(snapshotTimeStampNode.getTextContent().trim(), snapshotBuildNumberNode.getTextContent().trim());
    }    

    static File downloadArtifact(URL repositoryUrl, MavenArtifact artifact, String snapshotTimestamp, String snapshotBuildNumber) throws IOException
    {
        URL webAppUrl = MavenUtil.getArtifactUrl(repositoryUrl, artifact,  snapshotTimestamp, snapshotBuildNumber);

        Log.info("Downloading " + webAppUrl.toExternalForm());

        File warFile = File.createTempFile("MavenDeployer", ".war");

        byte[] buffer = new byte[32768];
        int length;

        InputStream is = webAppUrl.openStream();
        OutputStream os = new FileOutputStream(warFile);

        while ((length = is.read(buffer)) > 0) {
            os.write(buffer, 0, length);
        }

        is.close();
        os.close();

        return warFile;
    }
}
